<?php
namespace app\adminapi\model;
use app\common\controller\Common;
use app\common\lib\RedisServer;
use app\api\model\Role as RoleModel;
use think\Loader;
use think\Request;
use think\Db;
use app\api\model\Menu as MenuModel;

use PDO;
require_once "../vendor/Medoo/src/Medoo.php";
require_once '../vendor/autoload.php';
use Medoo\Medoo;
/**
 * @Author: Amor_L
 * @Date:   2020-06-05 14:03:24
 * @Last File:
 */
class Api extends Common
{
    
    protected $uid = 0;
    protected $style = 0;
    protected $user = [];

    public function initialize()
    {
        
        //不需要验证的方法
        $action_not_check_token = [
            'sendcode','login'
        ];
        //不需要验证的控制器
        $con_not_check_token = [
            'Userlogin'
        ];
        $con_action_check = [
            // 首页
            // 点击率排序
            'adminapi/Index/get_icon',
            // 点击量
            'adminapi/Index/save_icon',
            // 宴会累计数据
            'adminapi/Index/grand_total',
            // 宴会实时数据
            'adminapi/Index/index',

            // 订单
            // 获取客户经理
            'adminapi/Order/director',
            
            // 客户
            'adminapi/Client/index',
            'adminapi/Client/banquet_type',
            'adminapi/Client/source',

            // 权限
            'adminapi/Role/role',

            
            // 后台登陆
            'adminapi/Login/login'
            // 

            
        ];
        //获取产品
        parent::initialize();
        //后台增加允许跨域访问
        header('Access-Control-Allow-Headers: content-type,authorization,flag');
        header('Access-Control-Allow-Methods: PUT, GET, POST, DELETE');
        header('Access-Control-Allow-Origin: *');
        header('Content-Type: application/json; charset=utf-8');
        
        $action = $this->request->action();
        $controller = $this->request->controller();
        $now = 'adminapi/'.$controller.'/'.$action;
        // print_r($now);die;
        if(!in_array($controller,$con_not_check_token) && !in_array($action, $action_not_check_token)){
            $flag = input('server.HTTP_FLAG');
            if($flag){
                $uid = db('user_member')->where('flag',$flag)->where('type',2)->value('uid');
                if(!$uid){
                    echo json_encode(['code'=>'4','msg'=>'请登录']);die;
                }else{
                    $user = getuserinfo($uid);
                    if(!$user){
                        echo json_encode(['code'=>'4','msg'=>'请登录']);die;
                    }
                    if($user){
                        if($user['role']){
                            $role = explode(',',$user['role']);
                            $count = count($role);
                        
                            if($count == 1){
                                $role = db::name('admin_role')->where('id',$user['role'])->find();
                                if($role['pid'] != 0){
                                    $res = RoleModel::roleAuth($user['role']);
                                    $str1 =str_replace("[","",$res[0]);
                                    $str1 =str_replace("]","",$str1);
                                    $newArr = explode(',',$str1);
                                    $location = MenuModel::getLocation();
                                    $action   = end($location);
                                    if($action){
                                        foreach ($newArr as $kn => $vn) {
                                            $vn =str_replace('"',"",$vn);
                                            $newArr[$kn] = $vn;
                                        }
                                        if(!in_array($action['id'],$newArr)){
                                            if(!in_array($now,$con_action_check)){
                                                echo json_encode(['code'=>'1','msg'=>'暂无权限']);die;
                                            }
                                        }
                                        $this->user = $user;
                                    }
                                }else{
                                    $this->user = $user;
                                }
                            }elseif($count > 1){
                                $roles = db::name('admin_role')->where('id','in',$user['role'])->select();
                                if($roles){
                                    $menu = [];
                                    foreach ($roles as $ke => $ve) {
                                        if($ve['pid'] == 0){
                                            $is_supper = 1;
                                            break;
                                        }
                                        if($ve['pid'] != 0){
                                            $str1 =str_replace("[","",$ve['menu_auth']);
                                            $str1 =str_replace("]","",$str1);
                                            $newArr = explode(',',$str1);
                                            $menu = array_merge($newArr,$menu);
                                            $is_supper = 2;
                                        }
                                    }
                                    if($is_supper == 2){
                                        $location = MenuModel::getLocation();
                                        $action   = end($location);
                                        foreach ($newArr as $kn => $vn) {
                                            $vn =str_replace('"',"",$vn);
                                            $newArr[$kn] = $vn;
                                        }
                                        if(!in_array($action['id'],$newArr)){
                                            if(!in_array($now,$con_action_check)){
                                                echo json_encode(['code'=>'1','msg'=>'暂无权限']);die;
                                            }
                                        }
                                    }
                                    $this->user = $user;
                                }else{
                                    echo json_encode(['code'=>'1','msg'=>'角色不存在']);die;
                                }
                            }
                        }else{
                            echo json_encode(['code'=>'1','msg'=>'未分配权限']);die;
                        }
                    }
                }
            }else{
                echo json_encode(['code'=>'1','msg'=>'请登录']);die;
            }
        }
    }
    //返回数据格式
    protected function ajaxReturn($code,$msg,$data = [])
    {
        $action = $this->request->action();
        if($this->uid){
            // @RedisServer::unlock($this->uid.'/'.request()->module().'/'.request()->controller().'/'.request()->action());
            if(!isset($data)){
                return json(['code'=>"$code",'msg'=>$msg]);
            }
        }
        return json(['code'=>"$code",'msg'=>$msg,'data'=>$data]);
    }
    /**
     * @Access          public
     * @Method Name     database
     * @Purpose         数据库配置
     * @Return          数据库信息
     */ 
    public function database()
    {
        $database = new Medoo([
            // 必须配置项
            'database_type' => 'mysql',
            'database_name' => 'lu',
            'server' => '127.0.0.1',
            'username' => 'root',
            'password' => 'root',
            'charset' => 'utf8',
            // 可选参数
            'port' => 3306,
            // 可选，定义表的前缀
            'prefix' => 'ysx_',
            // 'socket' => '/Applications/MAMP/tmp/mysql/mysql.sock', //MAMP专用
            // 'option' => array(PDO::ATTR_CASE => PDO::CASE_NATURAL)
        ]);
        return $database;
    }
    /**
     * @Access          Base
     * @Method Name     getList 获取数据
     * @Purpose         查询数据
     * @data            需求数据可多条可单条
     * @where           约束条件可空
     * @Return          数据
     */ 
    public function getList($data,$where,$table){
        $database = $this->database();
        $list = $database->select("$table",$data,$where);
     
        return $list;
    }
    /**
     * @Access          Base
     * @Method Name     get 获取一条数据
     * @Purpose         查询数据
     * @data            需求数据单条
     * @where           约束条件不可空
     * @Return          数据
     */ 
    public function getone($data,$where,$tables){
        $database = $this->database();
        $list = $database->get("$tables",$data,$where);
        // var_dump( $database->log() );
        return $list;
    }
    /**
     * @Access          Base
     * @Method Name     insert  插入数据
     * @data            插入的数据
     * @tables          数据表
     * @Return          number
     */ 
    public function insert($tables,$data){
        $database = $this->database();
        $list = $database->insert("$tables",$data);
        $id = $database->id();
        return $id;
    }
    /**
     * @Access          Base
     * @Method Name     update  修改数据
     * @data            修改的数据
     * @where           约束条件
     * @tables          数据表
     * @Return          number
     */ 
    public function updates($tables,$data,$where){
        $database = $this->database();
        $list = $database->update("$tables",$data,$where);
        // var_dump( $database->log() );
        return $list;
    }
    /**
     * @Access          Base
     * @Method Name     del  删除数据
     * @where           约束条件
     * @tables          数据表
     * @Return          number
     */ 
    public function del($tables,$where){
        $database = $this->database();
        $list = $database->delete("$tables",$where);
        // var_dump( $database->log() );
        return $list;
    }
    /**
     * @Access          Base
     * @Method Name     getCount 计算行数
     * @count           需要统计的字段
     * @tables          查询数据表
     * @where           约束条件可空
     * @Return          数据
     */ 
    public function getCount($where,$tables){
        $database = $this->database();
        $list = $database->count("$tables",$where);
        // var_dump( $database->log() );
        return $list;
    }

}
